using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Book.Blog.Core.DTOs;
using Book.Blog.Core.Entities;
using Book.Blog.Core.Interfaces;

namespace Book.Blog.API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class UsersController : ControllerBase
    {
        private readonly UserManager<User> _userManager;
        private readonly IUnitOfWork _unitOfWork;

        public UsersController(UserManager<User> userManager, IUnitOfWork unitOfWork)
        {
            _userManager = userManager;
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 获取用户列表（需管理员，支持分页）
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns>用户分页列表</returns>
        [HttpGet]
        [Authorize(Roles = "Admin")]
        public async Task<ActionResult<UserPagedListDTO>> GetUsers([FromQuery] int pageIndex = 1, [FromQuery] int pageSize = 10)
        {
            var query = _userManager.Users.Where(u => !u.IsDeleted);
            var totalCount = await query.CountAsync();
            var items = await query
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .Select(u => new UserListDTO
                {
                    Id = u.Id,
                    UserName = u.UserName,
                    Email = u.Email,
                    Avatar = u.Avatar,
                    CreatedTime = u.CreatedTime,
                    EmailConfirmed = u.EmailConfirmed,
                    PostCount = u.Posts.Count
                })
                .ToListAsync();

            return new UserPagedListDTO
            {
                Items = items,
                TotalCount = totalCount,
                PageIndex = pageIndex,
                PageSize = pageSize,
                TotalPages = (int)Math.Ceiling(totalCount / (double)pageSize),
                HasPreviousPage = pageIndex > 1,
                HasNextPage = pageIndex < (int)Math.Ceiling(totalCount / (double)pageSize)
            };
        }

        /// <summary>
        /// 获取用户详情（需登录）
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>用户详情</returns>
        [HttpGet("{id}")]
        [Authorize]
        public async Task<ActionResult<UserDTO>> GetUser(Guid id)
        {
            var user = await _userManager.Users
                .Include(u => u.Posts)
                .Include(u => u.Followers)
                .Include(u => u.Following)
                .FirstOrDefaultAsync(u => u.Id == id && !u.IsDeleted);

            if (user == null)
            {
                return NotFound();
            }

            return new UserDTO
            {
                Id = user.Id,
                UserName = user.UserName,
                Email = user.Email,
                PhoneNumber = user.PhoneNumber,
                Avatar = user.Avatar,
                Bio = user.Bio,
                CreatedTime = user.CreatedTime,
                LastLoginTime = user.LastLoginTime,
                EmailConfirmed = user.EmailConfirmed,
                PhoneNumberConfirmed = user.PhoneNumberConfirmed,
                PostCount = user.Posts.Count,
                FollowersCount = user.Followers.Count,
                FollowingCount = user.Following.Count
            };
        }

        /// <summary>
        /// 更新个人资料（需登录）
        /// </summary>
        /// <param name="model">用户资料</param>
        /// <returns>无内容</returns>
        /// <remarks>
        /// 示例请求:
        /// {
        ///   "userName": "新昵称",
        ///   "bio": "个人简介",
        ///   "avatar": "头像URL"
        /// }
        /// </remarks>
        [HttpPut("profile")]
        [Authorize]
        public async Task<ActionResult> UpdateProfile(UpdateUserProfileDTO model)
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound();
            }

            if (!string.IsNullOrEmpty(model.UserName) && model.UserName != user.UserName)
            {
                var userNameExists = await _userManager.FindByNameAsync(model.UserName);
                if (userNameExists != null)
                {
                    return BadRequest("用户名已被使用");
                }
                user.UserName = model.UserName;
            }

            if (!string.IsNullOrEmpty(model.PhoneNumber) && model.PhoneNumber != user.PhoneNumber)
            {
                user.PhoneNumber = model.PhoneNumber;
                user.PhoneNumberConfirmed = false;
            }

            user.Avatar = model.Avatar ?? user.Avatar;
            user.Bio = model.Bio ?? user.Bio;
            user.UpdatedAt = DateTime.UtcNow;

            var result = await _userManager.UpdateAsync(user);
            if (!result.Succeeded)
            {
                return BadRequest(result.Errors);
            }

            return NoContent();
        }

        /// <summary>
        /// 关注用户（需登录）
        /// </summary>
        /// <param name="id">目标用户ID</param>
        /// <returns>无内容</returns>
        [HttpPost("{id}/follow")]
        [Authorize]
        public async Task<ActionResult> FollowUser(Guid id)
        {
            if (id == Guid.Parse(User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value))
            {
                return BadRequest("不能关注自己");
            }

            var currentUser = await _userManager.GetUserAsync(User);
            var targetUser = await _userManager.FindByIdAsync(id.ToString());

            if (targetUser == null)
            {
                return NotFound();
            }

            if (currentUser.Following.Contains(targetUser))
            {
                return BadRequest("已经关注过该用户");
            }

            currentUser.Following.Add(targetUser);
            await _userManager.UpdateAsync(currentUser);

            return NoContent();
        }

        /// <summary>
        /// 取消关注用户（需登录）
        /// </summary>
        /// <param name="id">目标用户ID</param>
        /// <returns>无内容</returns>
        [HttpDelete("{id}/follow")]
        [Authorize]
        public async Task<ActionResult> UnfollowUser(Guid id)
        {
            var currentUser = await _userManager.GetUserAsync(User);
            var targetUser = await _userManager.FindByIdAsync(id.ToString());

            if (targetUser == null)
            {
                return NotFound();
            }

            if (!currentUser.Following.Contains(targetUser))
            {
                return BadRequest("尚未关注该用户");
            }

            currentUser.Following.Remove(targetUser);
            await _userManager.UpdateAsync(currentUser);

            return NoContent();
        }

        /// <summary>
        /// 删除用户（需管理员）
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>无内容</returns>
        [HttpDelete("{id}")]
        [Authorize(Roles = "Admin")]
        public async Task<ActionResult> DeleteUser(Guid id)
        {
            var user = await _userManager.FindByIdAsync(id.ToString());
            if (user == null)
            {
                return NotFound();
            }

            user.IsDeleted = true;
            user.UpdatedAt = DateTime.UtcNow;
            await _userManager.UpdateAsync(user);

            return NoContent();
        }
    }
} 